﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;


namespace LGCourt.Logic.Common
{
    public class Utils
    {
        /// <summary>
        /// Encrypt the string
        /// Attention:key must be 8 bits
        /// </summary>
        /// <param name="strText">string</param>
        /// <param name="strEncrKey">key</param>
        /// <returns></returns>
        public static string DesEncrypt(string strText, string strEncrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());


            }
            catch (System.Exception error)
            {

                return "error:" + error.Message + "\r";
            }
        }
        /// <summary>
        /// Decrypt string
        /// Attention:key must be 8 bits
        /// </summary>
        /// <param name="strText">Decrypt string</param>
        /// <param name="sDecrKey">key</param>
        /// <returns>output string</returns>
        public static string DesDecrypt(string strText, string sDecrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[strText.Length];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch (System.Exception error)
            {

                return "error:" + error.Message + "\r";
            }
        }


        /// <summary>
        /// 截断字符串到指定的长度
        /// </summary>
        /// C#在获取字符串长度的时候，中文字为1，而数据库中为2，用此函数进行统一
        /// <remarks>
        /// </remarks>
        /// <param name="stringToSub">需要被截断的对象</param>
        /// <param name="length">需要截断的长度</param>
        public static string SubString(object stringToSub, int length)
        {
            string str = "";
            if (stringToSub == null)
                return null;
            else
                str = stringToSub.ToString();

            byte[] strByte = System.Text.Encoding.Default.GetBytes(str);
            int len = strByte.Length;
            if (len <= length) return str;

            //Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            Regex regex = new Regex("[^\x00-\xff]+", RegexOptions.Compiled);
            char[] stringChar = str.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;

            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    if (length - nLength > 1)
                    {
                        sb.Append(stringChar[i]);
                    }
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength >= length)
                    break;
            }
            sb.Append("...");
            return sb.ToString();
        }
        /// <summary>
        /// 将Unix的时间戳转换成时间
        /// </summary>
        /// <param name="unixstamp"></param>
        /// <returns></returns>
        public static DateTime ConvertUnixTimeStampToDateTime(string unixstamp)
        {
            //string timeStamp = "1257479110";
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(unixstamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }
        /// <summary>
        /// 将日期转换成mysql的unix时间戳
        /// </summary>
        /// <param name="dtaCmpr">要比较的日期</param>
        /// <returns></returns>
        public static uint ConvertDateTimeToUnixTimeStamp(DateTime dtaCmpr)
        {
            uint ret = 0;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan tmSpan = dtaCmpr - dtStart;
            if (dtaCmpr < dtStart) dtaCmpr = DateTime.Now.Date;
            string strTics = tmSpan.Ticks.ToString();
            if (strTics.Length > 7) ret = uint.Parse(strTics.Substring(0, strTics.Length - 7));
            return ret;
        }
        public static string GetTimestamp()
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();

            return timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
        }      

    }
}
